<template>
    <div class="map-template-main">
        <div class="container standard-map" >
            <div class="container" id="mapDiv"></div>
        </div>
        <div id="mapType-wrapper">
            <div id="mapType">
            <div class="mapTypeCard normal active" data-name="sl"><span>地图</span></div>
            <div class="mapTypeCard earth" data-name="yx"><span>影像</span></div>
            <div class="mapTypeCard panorama choosedType" data-name="panorama"> <span>全景</span></div>
            </div>
        </div>
        <div class="BMap_simple_bubble_center" id="click_overlay" style="z-index: 3; position: relative; height: 50px; width: 160px;background-color: rgb(255, 255, 255);" v-show="click_value !=''">
            <div class="BMap_simple_bubble_content" style="display: block; width: 160px; height: 50px; overflow: auto hidden;">
                <div id="poi_info_window" class="poi_info_window">    
                    <div class="left name_wrap" :title="click_value">                 
                        <span class="name">{{click_value}}</span>    
                    </div>
                </div>    
            </div>
        </div>
    </div>
</template>
<script>
    import $ from 'jquery'
    import Bus from '../../src/bus.js';
    export default {
        data() {
            return {
                olMap: {}, //地图对象ol
                olView:{},
                regionid:150000000,
                Layer_wms:null,//WMS图层
                Layer_poi: null, //search的地名图层 ol.source.Vector
                Filterlayer:null,
                OverFeature:null,
                click_Overlay:null,
                Wms_params:()=>{
                    return {
                        'FORMAT': 'image/png',
                        'VERSION': '1.1.0',
                        tiled: true,
                        STYLES: '',
                        LAYERS: 'xzqh:xzqh',  
                        SRS: "EPSG:3857",
                        CQL_FILTER: `code = ${this.regionid}`,
                        WIDTH:2180,
                        HEIGHT:900
                    }
                },
                click_value:'',
                
            }
        },
        mounted() {
            this.initmap();//初始化地图
            this.init_wrapper();
            Bus.$on('fly_to', (x,y) => {

                let point=new ol.geom.Point(ol.proj.transform([x, y],'EPSG:4326', 'EPSG:3857' ))
                this.ViewFlyTo(point,{
                    maxZoom:11
                });
            })
            Bus.$on('add_poi_marker', (item,index) => { //添加maker
                this.addPoiMarker(item,index)
            })
            Bus.$on('clear_poi_marker', () => { //清除maker
                this.clearPoiMarker()
            })
            Bus.$on('poi_marker_hover', (index,over_or_out) => {
                this.poi_marker_hover(index,over_or_out)
            })
        },
        methods: {
            init_wrapper(){
                let that=this;
                $("#mapType-wrapper").off('hover').hover(function(){
                    $(this).addClass("expand");
                },function(){
                    $(this).removeClass("expand");
                }).find(".mapTypeCard").off('click').click(function(){
                    var typeNew=$(this).attr("data-name");
                    var typeActive=$("#mapType-wrapper").find(".mapTypeCard.active").attr("data-name")
                    if(typeNew==typeActive){}
                    else{
                        $("#mapType-wrapper").find(".mapTypeCard").removeClass("active")
                        $(this).addClass('active')
                        that.wrapper_change(typeNew);
                    }
                    return false;
                })
            },
            wrapper_change(type){
                if(type=="sl"){
                    this.Groupvec.setVisible(true);
                    this.Groupimg.setVisible(false); 
                }
                else if(type=="yx"){
                    this.Groupvec.setVisible(false); 
                    this.Groupimg.setVisible(true); 
                }
            },
            //初始化地图
            initmap() {
                let that = this;
                let layers=this.TDTlayers();
                this.olView=new ol.View({
                    center: ol.proj.transform([114.35666406249996, 44.70117811999853],'EPSG:4326', 'EPSG:3857' ) ,
                    zoom:5,
                })
                this.olMap=new ol.Map({
                    controls:[],
                    target: 'mapDiv',
                    maxTilesLoading:16,
                    layers: layers,
                    view: this.olView
                })

               
                this.AddWms(); //WMS 模式渲染  速度快 但是没有鼠标交互 =.=
                this.AddmousePositionControl();//地图移动坐标显示控件


                this.AddpoiLayer();//查询的地名点maker图层

                //this.Add_image_satellite_Layer(); //测试影像快视图图层
                this.olMap.on('pointermove', (event)=>{ //鼠标的移入和移出要素
			        if(this.olMap.hasFeatureAtPixel(event.pixel)){
                        let Features=this.olMap.getFeaturesAtPixel(event.pixel,{
                            layerFilter:(layer)=>{
                                if(this.Filterlayer){
                                    return layer.ol_uid==this.Filterlayer.ol_uid;
                                }
                                else{
                                    return false;
                                }
                            }
                        })
                        if(Features.length>0){
                            let feature_over=Features[0];
                            if(this.OverFeature && this.OverFeature.ol_uid==feature_over.ol_uid){}
                            else{
                                feature_over.dispatchEvent({type: 'mousein', event: event,this:this});
                                this.OverFeature=feature_over
                            }
                        }
                    }
                    else{
                        if(this.OverFeature){
                            this.OverFeature.dispatchEvent({type: 'mouseout', event: event,this:this});
                            this.OverFeature=null;
                        }
                    }
                });
                this.olMap.on('click', (event)=>{ //鼠标的移入和移出要素
			        if(this.olMap.hasFeatureAtPixel(event.pixel)){
                        let Features=this.olMap.getFeaturesAtPixel(event.pixel,{
                            layerFilter:(layer)=>{
                                if(this.Filterlayer){
                                    return layer.ol_uid==this.Filterlayer.ol_uid;
                                }
                                else{
                                    return false;
                                }
                            }
                        })
                        if(Features.length>0){
                            let feature_over=Features[0];
                            feature_over.dispatchEvent({type: 'click', event: event,this:this});
                        }
                    }
                });
                
                
                
                this.olMap.on('movestart',()=>{
                    Bus.$emit('hide_card');
                })
            },
            on_over_out(layer){
                this.Filterlayer=layer;
            },
            off_over_out(){
                this.Filterlayer=null;
            },
            AddWms(){
                let TileWMS = new ol.source.TileWMS({
                    url: window.Glod.wms,
                    params: this.Wms_params(),
                    ratio:2,
                })
                this.Layer_wms = new ol.layer.Tile({
                    visible: true,
                    source: TileWMS
                });
                this.olMap.addLayer(this.Layer_wms)
            },
            AddmousePositionControl(){ //地图移动坐标显示控件
                var mousePositionControl=new ol.control.MousePosition({
                    coordinateFormat:ol.coordinate.createStringXY(3),
                    projection:"EPSG:4326",
                    className:"standard-map__mouse-position",
                    target:document.getElementById("mapDiv"),
                    undefinedHTML:"0,0"
                });
                this.olMap.addControl(mousePositionControl);
            },
            AddpoiLayer(){
                let poiSource = new ol.source.Vector({
                    features:[],
                    useSpatialIndex:false
                });
                this.Layer_poi = new ol.layer.Vector({
                    source: poiSource,
                });
                this.olMap.addLayer(this.Layer_poi)
                this.on_over_out(this.Layer_poi)
            },
            ViewFlyTo(geometryOrExtent,options){
                this.olView.fit(geometryOrExtent,{
                    duration:1000,
                    maxZoom:11
                })
            },
            TDTlayers(){
                this.Groupvec=new ol.layer.Group({
                    layers:[
                        new ol.layer.Tile({
                            source: new ol.source.XYZ({
                                url: "https://t{0-7}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=b4a8d92e2c4a1ec59beead8cf44d4ecb"
                            })
                        }),
                        new ol.layer.Tile({
                            source: new ol.source.XYZ({
                                url: "https://t{0-7}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=b4a8d92e2c4a1ec59beead8cf44d4ecb"
                            })
                        }),
                    ],
                    visible:true,
                })
                this.Groupimg=new ol.layer.Group({
                    layers:[
                        new ol.layer.Tile({
                            source: new ol.source.XYZ({
                                url: "https://t{0-7}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=b4a8d92e2c4a1ec59beead8cf44d4ecb"
                            })
                        }),
                        new ol.layer.Tile({
                            source: new ol.source.XYZ({
                                url: "https://t{0-7}.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=b4a8d92e2c4a1ec59beead8cf44d4ecb"
                            })
                        }),
            
                    ],
                    visible:false,
                })
                return [this.Groupvec,this.Groupimg]
            },
            addPoiMarker(item,index)
            {
                let feature=new ol.Feature({
                    geometry:new ol.geom.Point(ol.proj.transform([item.point[0], item.point[1]],'EPSG:4326', 'EPSG:3857' ))
                });
                feature.setProperties({
                    index:index,
                    prop:item
                },true)
                feature.setStyle(this.poi_maker_style(index))
                feature.on("mousein",(EventsKey)=>{
                    EventsKey.this.poi_marker_hover(EventsKey.target.values_.index,true)
                    //EventsKey.this.poi_marker_click(EventsKey.target.values_.index)
                });
                feature.on("mouseout",(EventsKey)=>{
                    EventsKey.this.poi_marker_hover(EventsKey.target.values_.index,false)
                    //EventsKey.this.poi_marker_click()
                });
                feature.on("click",(EventsKey)=>{
                    EventsKey.this.poi_marker_click(EventsKey.target.values_.index,false)
                    
                });
                if(this.Layer_poi){
                    this.Layer_poi.getSource().addFeature(feature)
                }
                
            },
            poi_marker_click(index){
                if(!index){
                    this.click_value=''
                    return
                }
                this.click_value=''
                let index_Feature=undefined
                this.Layer_poi.getSource().getFeaturesCollection().forEach((Feature)=>{
                    if(Feature.getProperties().index==index){
                        index_Feature=Feature;
                    }
                })
                this.click_value=index_Feature.values_.prop.standard_name
                let position=index_Feature.getGeometry()
                if(this.click_Overlay){
                    this.click_Overlay.setPosition(position.flatCoordinates)
                }
                else{
                    this.click_Overlay = new ol.Overlay({
                        element : document.getElementById('click_overlay'), 
                        id : 0,
                        position : position.flatCoordinates,
                        positioning : 'top-center',
                        offset:[0,-80]
                    });
                    this.olMap.addOverlay(this.click_Overlay);         
                }
            },
            clearPoiMarker(){
                if(this.Layer_poi){
                    this.Layer_poi.getSource().clear()
                }
                if(this.click_Overlay){
                    this.olMap.removeOverlay(this.click_Overlay);
                    this.click_Overlay=null;
                    this.click_value=null
                }
                
            },            
            poi_maker_style(index,bHover){
                let xoffset=21*(index - 1);
                let yoffset=0;
                if(bHover){
                    yoffset=33*2;
                }
                return  new ol.style.Style({
                    image: new ol.style.Icon({
                        src: 'https://nmgwxyy.cn/alatan/static/image_source/xzqh/markers.png',
                        offset:[xoffset,yoffset],
                        size:[21, 33],
                        imgSize:[300,300],
                        scale:1
                    }),
                });
            },
            
            poi_marker_hover(index,over_or_out){
                let index_Features=undefined
                this.Layer_poi.getSource().getFeaturesCollection().forEach((Feature)=>{
                    if(Feature.getProperties().index==index){
                        index_Features=Feature;
                    }
                })
                if(index_Features){
                    if(over_or_out){
                        index_Features.setStyle(this.poi_maker_style(index,true))
                        this.poi_marker_click(index)
                    }   
                    else{
                        index_Features.setStyle(this.poi_maker_style(index,false))
                        //this.poi_marker_click()
                    }
                    Bus.$emit('hover_indexs',index,over_or_out);
                }
            },
            
        },
    }
</script>
<style>
.poi_info_window {
    padding: 4px 0;
}
.poi_info_window .left {
    padding-left: 10px;
    padding-right: 10px;
    height: 40px;
    line-height: 16px;
    display: table;
    table-layout: fixed;
    width: 140px;
    text-align: center;
}
.poi_info_window .name_wrap {
    display: table-cell;
    vertical-align: middle;
}
.poi_info_window .name_wrap .name {
    font-size: 12px;
    font-weight: 700;
    word-wrap: break-word;
    overflow: hidden;
    display: block;
}
</style>